<?php
/**
 * @author spenceryg
 * @date 2022/1/30
 * @time 9:45 上午
 * @focus love & life
 */

namespace app\admin\controller\sys;

use app\admin\controller\sys\business\AdminUserBusiness;
use app\admin\service\AdminUser as AdminUserService;
use app\BaseController;
use think\App;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\View;
use think\response\Json;

/**
 * 后台登录
 * Class Login
 * @package app\admin\controller\sys
 */
class Login extends BaseController
{
    public $service;

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 后台登录
     * @return string|Json
     */
    public function index()
    {
        if (request()->isPost()) {
            $username = input('username', '');
            $password = input('password', '');
            $captcha = input('captcha', '');
            $data = [
                'username' => $username,
                'password' => $password,
                'captcha' => $captcha,
            ];
//            $this->checkLoginNum();
            AdminUserBusiness::login($data);
            $this->clearLoginNum();
            return success('登录成功', [], (string)url('sys.index/index'));
        } else {
            return View::fetch(app()->getAppPath() . 'controller/sys/view/login/index.html');
        }
    }

    //登录次数判断
    final private function checkLoginNum(){
        $ipName=md5($this->request->ip());
        $errorLoginNum=Cache::get($ipName);
        if($errorLoginNum>=config("login.error_num")){
            throw new ValidateException("登录次数已超出限制，请在".config("login.relogin_time")."分钟后再登录");
        }else{
            Cache::set($ipName,$errorLoginNum+1,config("login.relogin_time")*60);
        }
    }
    //清除登录次数判断
    final private function clearLoginNum(){
        $ipName=md5($this->request->ip());
        Cache::delete($ipName);
    }
}
